package com.erp.module.faHuoDanJu.faHuo1

import android.app.Activity
import android.content.Intent
import android.os.Environment
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import androidx.appcompat.app.AlertDialog
import com.erp.CaptureActivity
import com.erp.Interface.OnUserDataInterface
import com.erp.R
import com.erp.bean.ChedingdanBean
import com.erp.myAdapter.ChedingdanAdapter
import com.erp.myAdapter.PageivAdapter
import com.erp.myFragment.BaseKFragment
import com.erp.permission.PermissionListener
import com.erp.util.Httputil
import com.erp.util.JsonUtil
import com.erp.util.Myutil
import com.erp.util.PermissionUtils
import com.erp.view.MyAlerDialog
import kotlinx.android.synthetic.main.fragment_fahuo.*
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import org.xutils.x
import java.io.File
import java.util.*


/**
 * Created by Administrator on 2017/2/10/010.
 * 作者：刘洋
 * 单据页面
 */
class FragmentFahuo : BaseKFragment(), View.OnClickListener {
    /**
     * 订单的adapter
     */
    lateinit var adapter: ChedingdanAdapter
    /**
     * 本车订单
     */
    lateinit var chedingdanBeanList: MutableList<ChedingdanBean>
    /**
     * 是否已经拍过照
     */
    private val isphoto = false
    lateinit var pageivAdapter: PageivAdapter
    lateinit var inflater: LayoutInflater

    private var name = ""

    lateinit var dialog: AlertDialog
    lateinit var pageview: MutableList<View>
    lateinit var listname: MutableList<String>
    private var ivcode = -1
    companion object {
        val DANJU = 1
        val QINGDAN = 2
    }
    private val f = "FragmentFahuo"
    override fun getLayoutId(): Int {
        fragmentname = f
        return R.layout.fragment_fahuo
    }

    override fun initData() {
        chedingdanBeanList = ArrayList<ChedingdanBean>()
        adapter = ChedingdanAdapter(activity!!, chedingdanBeanList)
        LvCheDingdan.adapter = adapter
        pageview = ArrayList()
        listname = ArrayList()
        inflater = activity!!.layoutInflater
        pageiv(inflater)
        pageivAdapter = PageivAdapter(activity, pageview)
        VpIv.adapter = pageivAdapter
        IvScan.setOnClickListener(this)
        IvSousuo.setOnClickListener(this)
        BtShangchuan.setOnClickListener(this)
        BtChakan.setOnClickListener(this)
        BtChakanQd.setOnClickListener(this)
        BtShangchuanQd.setOnClickListener(this)
        EtQuery.setOnEditorActionListener { v, actionId, event ->
            var isOK = true
            when (actionId) {
                EditorInfo.IME_ACTION_SEARCH -> {
                    Myutil.notjianpan(activity, IvScan)
                    if (EtQuery.text.toString() != "") {
                        gethttpdanju(EtQuery.text.toString())
                    }
                }
                else -> isOK = false
            }
            isOK
        }
        val file = File(Environment.getExternalStorageDirectory().toString() + "/erp/photo")
        Myutil.deleteLfile(file)
    }
    override fun onClick(v: View) {
        when (v) {
            IvScan -> PermissionUtils.issaomiao(activity!!, object : PermissionListener {
                override fun onSucceed(requestCode: Int, grantPermissions: List<String>) {
                    val intent = Intent()
                    var a = activity
                    if(a != null){
                        intent.setClass(a, CaptureActivity::class.java)
                        intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
                        startActivityForResult(intent, 101)
                    }
                }

                override fun onFailed(requestCode: Int, deniedPermissions: List<String>) {
                    Myutil.MyTost("没有权限，无法扫描")
                }
            })
            IvSousuo -> {
                Myutil.notjianpan(activity, IvScan)
                if (EtQuery.text.toString() != "") {
                    gethttpdanju(EtQuery.text.toString())
                }
            }
            BtShangchuan -> {
                if (adapter.getlistoid().isEmpty() || name === "") {
                    return
                }
                PermissionUtils.isupdate(activity!!, object : PermissionListener {
                    override fun onSucceed(requestCode: Int, grantPermissions: List<String>) {
                        dialog = Myutil.showupdatedialog(activity, "正在上传单据", false)
                        for (i in listname.indices) {
                            sethttpdanju(listname[i], DANJU)
                        }
                    }

                    override fun onFailed(requestCode: Int, deniedPermissions: List<String>) {
                        Myutil.MyTost("没有权限，无法上传")
                    }
                })
            }
            BtChakan -> if (sp.getBoolean("ischakandanju", false)) {
                val intent = Intent(activity, MyFahuoActivity::class.java)
                intent.putExtra("type", DANJU)
                startActivity(intent)
            } else {
                val myAlerDialog = MyAlerDialog(activity)
                myAlerDialog.start()
                myAlerDialog.setdata("您不具备查看单据详情的权限，请找管理员索要")
                myAlerDialog.setleft("确定") { myAlerDialog.getdialog().dismiss() }
                myAlerDialog.show()
            }
            BtShangchuanQd -> {
                if (adapter.getlistoid().isEmpty() || name == "") {
                    return
                }
                PermissionUtils.isupdate(activity!!, object : PermissionListener {
                    override fun onSucceed(requestCode: Int, grantPermissions: List<String>) {
                        dialog = Myutil.showupdatedialog(activity, "正在上传清单", false)
                        for (i in listname.indices) {
                            val name = listname[i]
                            sethttpdanju(name, QINGDAN)
                        }
                    }

                    override fun onFailed(requestCode: Int, deniedPermissions: List<String>) {
                        Myutil.MyTost("没有权限，无法上传")
                    }
                })
            }
            BtChakanQd -> if (sp.getBoolean("ischakandanju", false)) {
                val intent = Intent(activity, MyFahuoActivity::class.java)
                intent.putExtra("type", QINGDAN)
                startActivity(intent)
            } else {
                val myAlerDialog = MyAlerDialog(activity)
                myAlerDialog.start()
                myAlerDialog.setdata("您不具备查看单据详情的权限，请找管理员索要")
                myAlerDialog.setleft("确定") { myAlerDialog.getdialog().dismiss() }
                myAlerDialog.show()
            }
        }
    }

    /**
     * @param requestCode 100为拍照，101为扫描
     * @param resultCode
     * @param data
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(data==null){
            return
        }
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                100 -> {
                    name = data.getStringExtra("dir")
                    Log.d("TAAAG", "dir===$name")
                    if (ivcode == listname.size) {
                        listname.add(name)
                    } else {
                        listname.removeAt(ivcode)
                        listname.add(ivcode, name)
                    }
                    pageiv(inflater)
                    pageivAdapter.notifyDataSetChanged()
                }
                101 ->  {
                    val bundle = data.extras
                    val s = bundle?.get("result") as String
                    EtQuery.setText(s)
                    gethttpdanju(s)
                }
            }
        }
    }

    /**
     * 网络访问获取专卖店订单
     *
     * @param keyworld 搜索关键词
     */
    private fun gethttpdanju(keyworld: String) {
        lvclean()
        dialog = Myutil.showupdatedialog(activity, "获取单据信息", false)
        Httputil.getdingdan(activity, keyworld, object : OnUserDataInterface {
            override fun onUserData(data: String?) {
                dialog.dismiss()
                if(data!=null) {
                    jsondata(data)
                }

            }

            override fun onNot(throwable: String) {
                dialog.dismiss()
            }
        })
    }
    /**清除显示的照片*/
    private fun lvclean() {
        adapter.cleanisb()
        chedingdanBeanList.clear()
        adapter.Allnotify(chedingdanBeanList)
        name = ""
    }

    /**
     * 解析订单数据
     */
    private fun jsondata(data: String) {

        try {
            val js = JSONArray(data)
            for (i in 0 until js.length()) {
                val jo = js.get(i) as JSONObject
                val chedingdanBean = ChedingdanBean()
                chedingdanBean.oid = JsonUtil.getvolue(jo, "oid")
                chedingdanBean.onum = JsonUtil.getvolue(jo, "onum")
                chedingdanBean.shop_name = JsonUtil.getvolue(jo, "shop_name")
                chedingdanBean.exclusive_shop = JsonUtil.getvolue(jo, "exclusive_shop")
                chedingdanBean.contract_num = JsonUtil.getvolue(jo, "contract_num")
                chedingdanBean.deliver_car = JsonUtil.getvolue(jo, "deliver_car")
                chedingdanBean.deliver_route = JsonUtil.getvolue(jo, "deliver_route")
                chedingdanBean.deliver_car_number = JsonUtil.getvolue(jo, "deliver_car_number")
                chedingdanBean.all_package_num = JsonUtil.getvolue(jo, "all_package_num")
                chedingdanBeanList.add(chedingdanBean)
            }
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        adapter.Allnotify(chedingdanBeanList)
        pageiv(inflater)
        pageivAdapter.notifyDataSetChanged()
    }


    private fun sethttpdanju(name: String, type: Int) {
        val names = name.split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[name.split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray().size - 1]
        Myutil.getbt(activity, name, object : OnUserDataInterface {
            override fun onUserData(data: String) {
                Httputil.setOploddanju(type, activity, adapter.getlistoid(), data, names, adapter.getlistcar(), object : OnUserDataInterface {
                    override fun onUserData(data: String) {
                        JsonUtil.toost(data)
                        dialog.dismiss()
                        EtQuery.setText("")
                        lvclean()
                        listname.clear()
                        VpIv.removeAllViews()
                        inflater = activity!!.layoutInflater
                        pageiv(inflater)
                        pageivAdapter.notifyDataSetChanged()
                    }

                    override fun onNot(throwable: String) {
                        dialog.dismiss()
                    }
                })
            }

            override fun onNot(throwable: String) {
                Myutil.MyTost("图片压缩失败")
            }
        })
    }

    fun pageiv(inflater: LayoutInflater) {
        pageview.clear()
        for (i in 0..listname.size) {
            val view = inflater.inflate(R.layout.vp_iv_item, null)
            val iv = view.findViewById<View>(R.id.iv_item) as ImageView
            if (i == listname.size) {
                if (chedingdanBeanList.size == 0) {
                    iv.setImageResource(R.mipmap.erp_null)
                } else {
                    iv.setImageResource(R.mipmap.erp_photo)
                }
            } else {
                x.image().bind(iv, listname[i])
            }
            iv.setOnClickListener(View.OnClickListener {
                if (chedingdanBeanList.size == 0) {
                    return@OnClickListener
                }
                PermissionUtils.isphoto(activity!!, object : PermissionListener {
                    override fun onSucceed(requestCode: Int, grantPermissions: List<String>) {
                        Myutil.photo(activity, this@FragmentFahuo, 1)
                        ivcode = i
                    }

                    override fun onFailed(requestCode: Int, deniedPermissions: List<String>) {
                        Myutil.MyTost("没有权限，无法拍照")
                    }
                })
            })
            pageview.add(view)
        }
    }
}
